package com.bjb.vr.auth.security;

import cn.hutool.extra.servlet.ServletUtil;
import com.bjb.vr.common.constant.LoginConstant;
import com.bjb.vr.common.constant.LoginTypeEnum;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.SysLogin;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.service.SysLoginService;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 登录失败处理器
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/8 10:16
 */
@Slf4j
@Component
public class RequestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Resource
    private SysLoginService sysLoginService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        UmsAccountVo umsAccountVo = new UmsAccountVo();
        ThreadLocalUtil.set(ThreadLocalConstant.USER_ACCOUNT_INFO, umsAccountVo);
        Map<String, String> parameters = (Map<String, String>) ThreadLocalUtil.get(ThreadLocalConstant.REQUEST_BODY);
        String errorMsg = authException.getMessage().replace("用户已失效", "该账号已被禁用");
        String username = parameters.get(LoginConstant.USER_NAME);
        String loginType = parameters.get(ThreadLocalConstant.LOGIN_TYPE);
        Map<String, Object> userInfo = sysLoginService.queryUserInfo(username, loginType);
        // 保存用户登录信息
        SysLogin sysLogin = new SysLogin();
        sysLogin.setLoginPlatform(LoginTypeEnum.valueOf(loginType.toUpperCase()).getLoginTypeValue());
        sysLogin.setUserName(username);
        sysLogin.setStatus(LoginConstant.LOGIN_FAILED);
        sysLogin.setIpaddr(parameters.get(ThreadLocalConstant.USER_HOST));
        sysLogin.setAccessTime(LocalDateTime.now());
        sysLogin.setMsg(errorMsg);
        if (userInfo.size() > 0) {
            sysLogin.setAccountId(Long.getLong(userInfo.get(ThreadLocalConstant.USER_ID).toString()));
            sysLogin.setTenantId(userInfo.get(ThreadLocalConstant.TENANT_ID).toString());
        }
        sysLoginService.saveLoginInfo(sysLogin);
        // 打印错误日志
        log.error(errorMsg);
        ThreadLocalUtil.remove(ThreadLocalConstant.REQUEST_BODY);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(CommonResult.Fail(errorMsg)));
    }
}
